/*
 * SpaceBattleInterface.cpp
 *
 *  Created on: Oct 23, 2011
 *      Author: gonzalo
 */

#include "SpaceBattleInterface.h"
#include "../persistencia/Persistor.h"
#include "../common/Translator/Translator.h"
#include "../common/Constantes.h"
#include "../common/DTOImage.h"

SpaceBattleInterface::SpaceBattleInterface(std::string scenarioName,bool) {
	this->scenarioName = scenarioName + ".xml";
	esServer =true;
	shipStatus = NULL;
	readXML();
}

SpaceBattleInterface::SpaceBattleInterface(std::string owner){
	this->owner = owner;
	esServer = false;
}
SpaceBattleInterface::~SpaceBattleInterface() {
	if (shipStatus != NULL)
		delete shipStatus;

	clearListDTOAsteroides();

	int status;

	status = rmdir(TEMP_DIR);

	//listAsteroides.clear();
	clearListAsteroides();
}

void SpaceBattleInterface::setShipStatus(ShipStatus* shipStatus){
	this->shipStatus = shipStatus;
}

ShipStatus* SpaceBattleInterface::getShip(){
	return shipStatus;
}

void SpaceBattleInterface::readXML(){
	int error = Persistor::getElements(this->scenarioName,this->listAsteroides);
	Persistor::getDimensions(this->scenarioName,&this->width,&this->height);

	if(error != PERSISTER_SUCCESS){
		Logger::log("SpaceBattleInterface","readXML","Error en la lectura del XML");
	}
}

std::list<Asteroide*> SpaceBattleInterface::getAsteroides(){
	if (esServer) {
		return listAsteroides;
	}

	return Translator::translateAsteroideDTO(listDTOAsteroides);
}


std::list< std::pair<std::string,std::string>* >* SpaceBattleInterface::getShips(){
	return Persistor::getShipsModels();
}

std::string SpaceBattleInterface::getOwner(){
	return this->owner;
}

void SpaceBattleInterface::setAsteroides(std::list<DTOAsteroide*> listElements){
	this->listDTOAsteroides = listElements;
}

int SpaceBattleInterface::getHeight() const
{
    return height;
}

int SpaceBattleInterface::getWidth() const
{
    return width;
}

void SpaceBattleInterface::clearListDTOAsteroides(){
	//Borrar los asteroides si se pasaron por red
	DTOAsteroide* dtoAux = NULL;
	DTOImage* imageToDelete;
	while(!listDTOAsteroides.empty()){
		dtoAux = listDTOAsteroides.back();
		imageToDelete = new DTOImage(dtoAux->tipo->imagePath);

		if(imageToDelete->deleteImagen()){
			Logger::log("SpaceBattleInterface","clearListDTOAsteroides","Fallo al borrar la imagen que se transfirio desde el servidor.");
			Logger::log("SpaceBattleInterface","clearListDTOAsteroides","Imagen Fallida : " + imageToDelete->getImagePath());
		}


		delete imageToDelete;
		delete dtoAux;

		listDTOAsteroides.pop_back();
	}
}

void SpaceBattleInterface::clearListAsteroides(){
	//Borrar los asteroides
	listAsteroides.clear();
}

void SpaceBattleInterface::setPlayScenarioDimensions(int width,int height){
	this->width = width;
	this->height = height;
}

void SpaceBattleInterface::resetClientInterface(){
	clearListDTOAsteroides();
	clearListAsteroides();
	readXML();
}

